import { uploadFileBySys } from '@/services/ant-design-pro/api';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { useEffect, useState } from 'react';
export const TextEditor = (
  props: {
    value?: string;
    readonly?: boolean;
    onChange?: (value?: string) => string | undefined;
  } = {},
) => {
  const [data, setData] = useState<any>({});
  const initContent = (c = '') => {
    const editorState = BraftEditor.createEditorState(c || '');
    return editorState;
  };
  useEffect(() => {
    if (props.value) {
      const contentStatus = initContent(props.value);
      data.contentStatus = contentStatus;
      setData({ ...data });
    }
  }, []);
  const uploadFn = (param: TextMediaParamsType) => {
    const successFn = (response: any) => {
      // 上传成功后调用param.success并传入上传后的文件地址
      param.success({
        url: response.data,
      });
    };
    const progressFn = (event: ProgressEvent) => {
      // 上传进度发生变化时调用param.progress
      param.progress((event.loaded / event.total) * 100);
    };
    const errorFn = (_response: any) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.',
      });
    };
    const options: ProgressTypes = {
      onUploadProgress: progressFn,
    };

    uploadFileBySys({ file: param.file }, options)
      .then((res: any) => {
        if (res.code === 200) {
          successFn(res);
        } else {
          errorFn(res);
        }
      })
      .catch((err: any) => {
        errorFn(err);
      });
  };

  return (
    <BraftEditor
      placeholder="请输入内容"
      className='full-width'
      style={{ border: '1px solid #ccc' }}
      value={data?.contentStatus}
      media={{ uploadFn }}
      readOnly={props.readonly}
      // extendControls={extendControls}
      onChange={(e: any) => {
        data.contentStatus = e;
        setData({ ...data });
        if (props && props.onChange) {
          props.onChange(e.toHTML());
        }
      }}
    />
  );
};
